import { ref } from 'vue';

const Sign = R.prop(R.__, { small: -1, big: 1 });

export function useScale(app) {
  const percentage = ref(100);
  const minPercentage = ref(100);
  const maxPercentage = ref(300);

  /** @param {'small' | 'big'} s */
  const scaleChangeTo = s => {
    const add = sign => percentage.value + sign;
    const Limiter = () => R.clamp(minPercentage.value, maxPercentage.value);
    const set = v => percentage.value = v;
    return R.compose( set, Limiter(), add, Sign )(s);
  };

  const calcPctAtContain = sprite => {
    const pctOn = R.converge( R.divide, [R.prop(R.__, app.screen), R.prop(R.__, sprite)] );
    return Math.min(
      ...R.map(
        R.compose( Math.floor, R.multiply(100), pctOn ),
        ['width', 'height']
      )
    );
  };

  // - [ ] 图片实际尺寸偏小，适合视图比例会大于 100%，控制点缩放比例略不美观
  /**
   * 期望数值转对应比例，同时保证比例在有效范围内
   * @param {number} v 框线宽或标签字号之类
   */
  const calcOnPct = v => v / ( Math.min(percentage.value, 100) / 100 );

  const elemPosInCenterOfScreen = elem => ({
    x: (app.screen.width - elem.width) * .5,
    y: (app.screen.height - elem.height) * .5,
  });

  return {
    percentage,
    minPercentage,
    maxPercentage,
    scaleChangeTo,
    calcPctAtContain,
    calcOnPct,
    elemPosInCenterOfScreen,
  };
}
